package org.fuxia.im.core.service.impl;

import javax.annotation.Resource;

import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.entries.ECResponse;
import org.fuxia.im.core.entries.ECSession;
import org.fuxia.im.core.server.ECSessionMananger;
import org.fuxia.im.core.socket.impl.ECNioServer;
import org.fuxia.im.db.dao.ChatGroupDaoImpl;
import org.fuxia.im.db.dao.UserChatGroupDaoImpl;
import org.fuxia.im.entities.ChatGroup;
import org.fuxia.im.entities.UserChatGroup;
import org.springframework.stereotype.Service;

@Service(value="ADD_GROUP")
public class AddGroupApplyService extends AbstractService {

	@Resource
	private UserChatGroupDaoImpl ucgDao ;
	
	@Resource
	private ChatGroupDaoImpl cgd ;
	
	public void service(ECPacket packet) {
		String isAgree = packet.getParameter("isAgree") ;
		
		//当isAgree不为空的时候即表示这是一个申请加入的请求
		if(isAgree!= null) {
			ECResponse resp = new ECResponse() ;
			resp.setResponseType("GROUP_ADD_RESULT");
			resp.setStatusCode(200);
			String userCode = packet.getParameter("userCode");
			boolean isAgreeB = Boolean.parseBoolean(isAgree) ;
			if(isAgreeB) {
				UserChatGroup ucg = new UserChatGroup() ;
				ucg.setChatGroupId(packet.getParameter("groupId")) ;
				ucg.setNickName(packet.getParameter("nickName")) ;
				ucg.setUserCode(userCode) ;
				try{
					ucgDao.saveOrUpdate(ucg);
					ChatGroup cg = cgd.findByGroupId(ucg.getChatGroupId()) ;
					resp.put("new_group", cg);
					resp.setResponseText("你好，群主[" + packet.getParameter("ownerId") + "] 已同意你加入该群") ;
				}catch (Exception e) {
				}
			}else {
				resp.setResponseText("对方拒绝你的入群申请") ;
			}
			
			//获取当前发起请求的用户的Session
			ECSession session = ECSessionMananger.getInstance().getUserSession(packet.getParameter("userCode")) ;
			if(session!= null) {
				try {
					ECNioServer.writeResponse(resp, session.getChannel()) ;
				} catch (Exception e) {
					//no ops
				}
			}
		}else{
			//获取群组拥有者的Session
			ECSession session = ECSessionMananger.getInstance().getUserSession(packet.getParameter("ownerId")) ;
			if(session!= null) {
				try {
					ECNioServer.sendPacket(packet, session.getChannel()) ;
				} catch (Exception e) {
					//no ops
				}
			}
		}
	}

}
